"""
Socket5服务器 - 处理客户端连接
"""
import socket
import threading
import json
import uuid
import logging
from datetime import datetime
from database import Database, AccountManager, ClientManager
from config import SERVER_HOST, SERVER_PORT

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class SocketServer:
    def __init__(self):
        self.db = Database()
        self.account_manager = AccountManager(self.db)
        self.client_manager = ClientManager(self.db)
        self.clients = {}  # {client_id: socket}
        self.running = False

    def start(self):
        """启动服务器"""
        self.running = True
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind((SERVER_HOST, SERVER_PORT))
        self.socket.listen(10)
        logger.info(f"Socket服务器启动在 {SERVER_HOST}:{SERVER_PORT}")

        while self.running:
            try:
                client_socket, address = self.socket.accept()
                client_thread = threading.Thread(
                    target=self.handle_client,
                    args=(client_socket, address)
                )
                client_thread.daemon = True
                client_thread.start()
            except Exception as e:
                if self.running:
                    logger.error(f"接受连接时出错: {e}")

    def handle_client(self, client_socket, address):
        """处理客户端连接"""
        client_id = None
        try:
            # 接收认证信息
            data = client_socket.recv(1024).decode('utf-8')
            if not data:
                return

            message = json.loads(data)
            action = message.get('action')

            if action == 'login':
                username = message.get('username')
                password = message.get('password')

                # 验证账号
                if self.account_manager.verify_account(username, password):
                    client_id = str(uuid.uuid4())
                    self.clients[client_id] = client_socket
                    self.client_manager.add_client(client_id, username, address[0])
                    
                    response = {
                        'status': 'success',
                        'message': '登录成功',
                        'client_id': client_id
                    }
                    client_socket.send(json.dumps(response).encode('utf-8'))
                    logger.info(f"客户端 {username} ({client_id}) 登录成功")

                    # 保持连接
                    self.keep_alive(client_socket, client_id)
                else:
                    response = {
                        'status': 'error',
                        'message': '用户名或密码错误'
                    }
                    client_socket.send(json.dumps(response).encode('utf-8'))
                    client_socket.close()
            else:
                response = {
                    'status': 'error',
                    'message': '未知操作'
                }
                client_socket.send(json.dumps(response).encode('utf-8'))
                client_socket.close()

        except Exception as e:
            logger.error(f"处理客户端时出错: {e}")
        finally:
            if client_id and client_id in self.clients:
                del self.clients[client_id]
                self.client_manager.update_client_status(client_id, 'offline')
            client_socket.close()

    def keep_alive(self, client_socket, client_id):
        """保持连接活跃"""
        try:
            while self.running:
                data = client_socket.recv(1024)
                if not data:
                    break
                # 可以处理心跳包或其他消息
                message = json.loads(data.decode('utf-8'))
                if message.get('action') == 'heartbeat':
                    response = {'status': 'ok'}
                    client_socket.send(json.dumps(response).encode('utf-8'))
        except Exception as e:
            logger.error(f"保持连接时出错: {e}")

    def stop(self):
        """停止服务器"""
        self.running = False
        if hasattr(self, 'socket'):
            self.socket.close()
        self.db.close()
        logger.info("Socket服务器已停止")

    def send_to_client(self, client_id, message):
        """向指定客户端发送消息"""
        if client_id in self.clients:
            try:
                self.clients[client_id].send(json.dumps(message).encode('utf-8'))
                return True
            except Exception as e:
                logger.error(f"发送消息失败: {e}")
                return False
        return False

